# Copyright (c) [2019] Huawei Technologies Co., Ltd.
# generic-release is licensed under the Mulan PSL v1.
# You can use this software according to the terms and conditions of the Mulan PSL v1.
# You may obtain a copy of Mulan PSL v1 at:
#     http://license.coscl.org.cn/MulanPSL
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v1 for more details.

# Copy from openEuler20.03: /etc/profile.d/system-info.sh

# show system information
function system_info() {
    # kernel release
    kernel_release=$(uname -r)
    # Operating system
    os_name=$(hostnamectl | grep "Operating System" | awk -F':' '{print $2}')

    # Memory
    memory_total=$(free -m | awk '/Mem:/ { printf($2)}')
    if [ $memory_total -gt 0 ]; then
        memory_usage=$(free -m | awk '/Mem:/ { printf("%3.1f%%", $3/$2*100)}')
    else
        memory_usage=0.0%
    fi

    # Swap memory
    swap_total=$(free -m | awk '/Swap:/ { printf($2)}')
    if [ $swap_total -gt 0 ]; then
        swap_mem=$(free -m | awk '/Swap:/ { printf("%3.1f%%", $3/$2*100)}')
    else
        swap_mem=0.0%
    fi

    # Usage
    usageof=$(df -h / | awk '/\// {print $(NF-1)}')
    # System load
    load_average=$(awk '{print $1}' /proc/loadavg)
    # WHO I AM
    whoiam=$(whoami)
    # Time
    time_cur=$(date)
    # Processes
    processes=$(ps aux | wc -l)
    # Users
    user_num=$(users | wc -w)
    # Ip address
    ip_pre=$(/sbin/ip a|grep inet|grep -v 127.0.0.1|grep -v inet6 | awk '{print $2}' | head -1)
    ip_address=${ip_pre%/*}
    # system boot time
    boot_time=$(uptime -s)

    echo -e "\n"
    echo -e "Welcome to $os_name $kernel_release\n"
    echo -e "System information as of time: \t$time_cur\n"
    echo -e "System load: \t\033[0;33;40m$load_average\033[0m"
    echo -e "Processes: \t$processes"
    echo -e "boot time: \t$boot_time"
    echo -e "Memory used: \t$memory_usage"
    echo -e "Swap used: \t$swap_mem"
    echo -e "Root usage: \t$usageof"
    echo -e "IP address: \t$ip_address"
    echo -e "Users online: \t$user_num\n"
    if [ "$whoiam" == "root" ]; then
      echo -e "\n"
    else
      echo -e "To run a command as administrator(user \"root\"),use \"sudo <command>\"."
    fi
}

system_info